package com.ophiux.common.core.exception;

import com.ophiux.common.core.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: hhl
 * @date：2022/8/19 16:25
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(Exception.class)
	public Result handleException(Exception e) {
		log.error("服务异常：{}", e);
		return Result.fail("服务异常");
	}

	@ExceptionHandler(RuntimeException.class)
	public Result handleRuntimeException(RuntimeException e) {
		log.error("运行时异常信息 ex={}", e);
		return Result.fail("服务异常");
	}

	@ExceptionHandler(SQLException.class)
	public Result handleSQLException(SQLException e) {
		log.error("SQL执行异常信息 ex={}", e);
		return Result.fail("数据处理异常");
	}


//	@ExceptionHandler(RetryableException.class)
//	public Result handleException(RetryableException e) {
//		log.error("Feign调用异常信息 ex={}", e);
//		return Result.failed("服务连接异常");
//	}

//	@ExceptionHandler(FeignException.class)
//	public R handleException(FeignException e) {
//		log.error("Feign调用异常信息 ex={}", e);
//		return R.failed("服务连接异常");
//	}

//	@ExceptionHandler(WxErrorException.class)
//	public R handleException(WxErrorException e) {
//		log.error("微信接口异常信息 ex={}", e);
//		return R.failed("微信服务异常");
//	}


	@ExceptionHandler(TooManyResultsException.class)
	public Result handleException(TooManyResultsException e) {
		log.error("数据库执行异常信息 ex={}", e);
		return Result.fail("数据处理异常");
	}

	@ExceptionHandler(NumberFormatException.class)
	public Result handleException(NumberFormatException e) {
		log.error("数字转化异常信息 ex={}", e);
		return Result.fail("服务异常");
	}

	@ExceptionHandler(BuilderException.class)
	public Result handleException(BuilderException e) {
		log.error("SQL执行异常信息 ex={}", e);
		return Result.fail("服务异常");
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result handleException(MethodArgumentNotValidException e) {
		log.info("参数不齐异常：{}", e);
		StringBuilder sb = new StringBuilder();
		List<ObjectError> allinfos = e.getBindingResult().getAllErrors();
		String message = allinfos.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining("；"));
		return Result.fail(message);
	}

}
